import router from '@/router';
import useStore from '@/store';
import { thirdLlogin } from '@/api/user';
import Cookies from 'js-cookie';
import { ElMessage } from 'element-plus';

// 白名单路由
const whiteList = ['/login', '/register'];
const key = {
  userNameKey: 'wdd-user-web-user-name',
  realNameKey: 'wdd-user-web-real-name'
};
router.beforeEach(async (to, from, next) => {
  console.log("to,from==",to, from);

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  if (window._hmt && to.path) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    window._hmt.push(['_trackPageview', `/#${to.path}`]);
  }

  const { user } = useStore();
  const hasToken = user.token;
  const pSign = to.query.pSign;
  if (pSign) {
    await thirdLlogin({ pSign: pSign }).then(res => {
      if (res.code == 1) {
        const loginData = res.response;
        const expries = new Date(res.response.endTime);
        Cookies.set(key.userNameKey, loginData.userName, { expires: expries });
        Cookies.set(key.realNameKey, loginData.realName, { expires: expries });
        Cookies.set(import.meta.env.VITE_APP_TOKEN_KEY, loginData.token, {
          expires: expries
        });
        user.userName = loginData.userName;
        user.realName = loginData.realName;
        user.token = loginData.token;
        next({ path: '/' });
      } else {
        ElMessage.error('数据解析失败');
        next(`/login?redirect=${to.path}`);
      }
    });
  } else {
    if (hasToken) {
      // 登录成功，跳转到首页
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        next();
      }
    } else {
      // 未登录可以访问白名单页面(登录页面)
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.path}`);
      }
    }
  }
});
